package fn;

public class Add extends Function {
	private static final long serialVersionUID = 6789433641023496136L;

	private Function[] child;

	private Add(Function f0, Function f1) {
		child = new Function[] {
				f0, f1 };
	}

	public static Function create(Function f0, Function f1) {
		// rule 1 : adding 0
		if(f0 instanceof Constant && f0.evaluate(0) == 0)
			return f1;
		if(f1 instanceof Constant && f1.evaluate(0) == 0)
			return f0;
		// rule 2 : adding two constants
		return new Add(f0, f1);
	}

	@Override
	protected Function[] child() {
		return child;
	}

	@Override
	public double evaluate(double sub) {
		return child[0].evaluate(sub) + child[1].evaluate(sub);
	}

	@Override
	public String prefix() {
		return "";
	}

	@Override
	public String infix() {
		return " + ";
	}

	@Override
	public String postfix() {
		return "";
	}

	@Override
	protected int precedence() {
		return 1;
	}

	@Override
	protected boolean withPar() {
		return true;
	}

	@Override
	public Function derivative() {
		Function out = create(child[0].derivative(), child[1].derivative());
		return out;
	}

}
